package com.fit.config;


import com.fit.realm.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroRealm shiroRealm(){
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //设置realm
        defaultWebSecurityManager.setRealm(shiroRealm());
        return defaultWebSecurityManager;
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
        //创建过滤map
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //放行路径
        map.put("/loginController/**",DefaultFilter.anon.name());
        //放行静态资源
        map.put("/js/**",DefaultFilter.anon.name());
        //退出登录
        map.put("/loginController/loginOut",DefaultFilter.logout.name());
        //拦截/shiro/路径下的所有
        map.put("/**", DefaultFilter.authc.name());
        //放入过滤器中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //配置登录页面

        //没有权限跳转的页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("/loginController/unauthorized");

        return shiroFilterFactoryBean;
    }
    //解密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(8);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }


}
